package com.miya.demo.common.util;

import com.miya.demo.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.Lock;

/**
 * redisson锁工具类
 *
 * @author Caixiaowei
 * @date 2022/06/21
 */
@Component
@Slf4j
public class RedissonLockUtil {

    private static final long DEFAULT_WAIT_TIME = 5L;

    @Autowired
    RedissonClient redissonClient;

    /**
     * 加锁后运行
     *
     * @param lockName 锁名称
     * @param runnable Runnable
     */
    public void runWithLock(String lockName, Runnable runnable) {
        Lock lock = redissonClient.getLock(lockName);
        runWithLock(lock, lockName, DEFAULT_WAIT_TIME, runnable, true);
    }

    /**
     * 加锁后运行
     *
     * @param lockName 锁名称
     * @param waitTime 等待时间，超过之后取锁失败
     * @param runnable Runnable
     */
    public void runWithLock(String lockName, Long waitTime, Runnable runnable) {
        Lock lock = redissonClient.getLock(lockName);
        runWithLock(lock, lockName, waitTime, runnable, true);
    }

    public void runWithLock(Lock lock, String lockName, Long waitTime, Runnable runnable, boolean logEnabled) {
        if (waitTime == null) {
            waitTime = DEFAULT_WAIT_TIME;
        }
        try {
            boolean lockOn = lock.tryLock(waitTime, java.util.concurrent.TimeUnit.SECONDS);
            if (lockOn) {
                if (logEnabled) {
                    log.info("Try lock [{}] success.", lockName);
                }
                try {
                    runnable.run();
                } finally {
                    lock.unlock();
                }
            } else {
                throw new BusinessException(String.format("Try lock [%s] fail.", lockName));
            }
        } catch (InterruptedException e) {
            if (logEnabled) {
                log.info("Try lock [{}] fail with exception.", lockName);
            }
            throw new BusinessException(e);
        }
    }

}
